<template>
	<view class="content" :style="{ height: windowHeight + 'px' }">
		<u--form :model="model1" :rules="rules" ref="uForm" labelWidth="80">
			<u-form-item label="地址" prop="recipientAddr" @click="showType = true;">
				<u--input v-model="model1.recipientAddr" disabled placeholder="请选择" suffixIcon="arrow-down"
					suffixIconStyle="rgb(172, 172, 172)"></u--input>
			</u-form-item>
		</u--form>
		<view class="buttons" @click="submits">
			立即抢购
		</view>

		<!-- 类别 -->
		<u-picker keyName="name" @confirm="confirm($event, '地址')" closeOnClickOverlay title="地址" :show="showType"
			:columns="typeColumns" @close="showType = false" @cancel="showType = false"></u-picker>
	</view>
</template>

<script>
	import {
		systemInfo
	} from '../../utils/mixin'
	import {
		userAddrMylist,
		buyGoods,
		decodeOpenid,
		payOrder,
		createOrderForApp
	} from '@/api/index.js'
	export default {
		mixins: [systemInfo],
		data() {
			return {
				showType: false,
				typeColumns: [],
				model1: {
					recipientAddr: '',
				},
				rules: {
					recipientAddr: [{
						type: 'string',
						required: true,
						message: '请选择地址',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		async onLoad(options) {
			// 状态栏高度
			this.getSystemInfo();
			this.productId = options.productId

			// 地址
			const res = await userAddrMylist({})
			res.rows.forEach((element, index) => {
				element.names = element.name
				element.name = element.provinceName + (element.cityName == '市辖区' ? '' : element.cityName) +
					element.areaName + element.address
				element.value = index
			});
			this.typeColumns = [res.rows]
		},
		methods: {
			//弹出框确定按钮
			confirm(value, name) {
				if (name == "地址") {
					this.model1.recipientAddr = value.value[0]?.name;
					const datas = this.typeColumns[0][value.value[0]?.value]
					this.model1.recipientName = datas.names
					this.model1.recipientPhone = datas.phone
					this.model1.recipientProvinceName = datas.provinceName
					this.model1.recipientProvinceCode = datas.provinceCode
					this.model1.recipientCityName = datas.cityName
					this.model1.recipientCityCode = datas.cityCode
					this.model1.recipientAreaName = datas.areaName
					this.model1.recipientAreaCode = datas.areaCode
					this.model1.recipientAddress = datas.address
					this.showType = false
				}
			},
			submits() {
				this.$refs.uForm.validate().then(async (valid) => {
					if (valid) {

						const response = await buyGoods({
							productId: this.productId,
							...this.model1
						})
						if(response.code != 200){
							return 
						}
						const that = this
						// #ifdef APP-PLUS
						createOrderForApp({
							outTradeNo: response.data.outTradeNo,
							totalFee: response.data.totalFee,
							body: "购买商品"
						}).then(res => {
							const orderInfo = {
								package: res.data.package,
								appid: res.data.appid,
								sign: res.data.sign,
								partnerid: res.data.partnerid,
								prepayid: res.data.prepayid,
								noncestr: res.data.noncestr,
								timestamp: res.data.timestamp
							}
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo:orderInfo,
								success(res) {
									if (res.errMsg ==
										"requestPayment:ok") {
										console.log('支付成功',
											res)
										uni.$u.toast("抢购成功")
										setTimeout(() => {
											uni.navigateBack({
												delta: 1
											});
										}, 2000)

									} else {
										console.log('支付失败')
									}
								},
								fail(res) {
									console.log('支付失败', res)
								}
							})
						})
						// #endif
						// #ifdef MP-WEIXIN
						await uni.login({
							provider: 'weixin',
							success(res) {
								if (res.code) {
									// 根据code获取openid
									decodeOpenid({
										code: res.code,
									}).then(res => {
										// 获取支付核心参数，预支付
										payOrder({
											totalFee: response.data.totalFee,
											outTradeNo: response.data.outTradeNo,
											body: response.data.body,
											openid: res.msg
										}).then(res => {
											// 支付
											wx.requestPayment({
												timeStamp: res.data.body
													.timeStamp, //时间戳
												nonceStr: res.data.body
													.nonceStr, //随机字符串
												package: res.data.body
													.package, //prepay_id
												signType: res.data.body
													.signType, //签名算法MD5
												paySign: res.data.body
													.paySign, //签名
												success(res) {
													if (res.errMsg ==
														"requestPayment:ok") {
														console.log('支付成功',
															res)
														uni.$u.toast("抢购成功")
														setTimeout(() => {
															uni.navigateBack({
																delta: 1
															});
														}, 2000)

													} else {
														console.log('支付失败')
													}
												},
												fail(res) {
													console.log('支付失败', res)
												}
											})
										})
									})
								} else {
									console.log('登录失败！' + res.errMsg)
								}
							},
							fail(res) {
								console.log('登录失败！' + JSON.stringify(res))
							}
						})
						// #endif
					}
				})
			},
		}
	}
</script>

<style lang="less" scoped>
	.content {
		background-color: #fff;
		width: 100%;
		box-sizing: border-box;
		padding: 40rpx;

		/deep/ .u-textarea {
			background-color: rgb(245, 247, 250);
		}

		.buttons {
			margin: 50rpx auto 0;
			width: 300rpx;
			height: 80rpx;
			background-color: rgba(34, 175, 229);
			color: #fff;
			line-height: 80rpx;
			text-align: center;
			font-size: 36rpx;
			border-radius: 10rpx;
			letter-spacing: 20rpx;
		}

		.flex {
			display: flex;
			align-items: center;
			margin-top: 20rpx;

			.image-title {
				margin-right: 20rpx;
				width: 70rpx;
			}
		}
	}
</style>